<?php
/**
 * Created by PhpStorm.
 * User: william
 * Date: 16-8-31
 * Time: 下午2:44
 */
namespace V4;
class C_ProductList extends \V3\C_ProductList {

    public function get(array $req,array $post,&$result)
    {
        // 验证开始
        if (!isset($req['uid'])) {return 'require user id ';}
        if (!isset($req['userType'])) {return 'require user type';}
        if (!isset($req['k']) || !isset($req['t']))  {return 'data error';}
        if (!isset($req['enterpriseId']))  {return 'require enterprise id';}
        if (!isset($req['channelId'])) {return 'require channel id';}
        if (\Biz\UserHandler::checkAuth($req['userType'],$req['uid'],$req['enterpriseId'],$req['t'],$req['k']) == false) {
            return 'data illegal';
        }
        $customer_handler = new \Biz\UserHandler();
        $customer_cls = $customer_handler ->getById($req['userType'],$req['uid']);
        if(!is_object($customer_cls) && $customer_cls->getEnterpriseId() ==false){
            return 'data error';
        }
        $channel_id = $customer_cls ->getChannelId();
        $enterprise_id = $customer_cls ->getEnterpriseId();
        if ($channel_id != $req['channelId']) {    //验证用户渠道
            return 'invalid channel id ';
        }
        if ($enterprise_id != $req['enterpriseId']) {//验证用户企业
            return 'invalid enterprise id ';
        }
        // 验证结束
        $tags = isset($req['tags']) ? $req['tags'] : '';   //$req['tags'] = '1:3,6;5:8';

        $fliter_product_ids = array(); //  筛选得到的商品id 数组
        if(!empty($tags)) {
            $tagsarr = explode(';', $tags);
            $new_tags = array();
            foreach ($tagsarr as $group_tags) {
                $group = explode(':', $group_tags);
                $new_tags[$group[0]] = $group[1];
            }
            $tags_biz = new \Biz\TagsHandler();
            $fliter_product_ids = $tags_biz->getProductIdByTagsId($new_tags);
            $fliter_product_ids = $this->low_array_column($fliter_product_ids, 'product_id');
        }

        //获取渠道下所有在售产品
        $product_channel_handler = new \Biz\ProductHandler();
        if($fliter_product_ids) {
            $product_channel_lists = $product_channel_handler->getOnsaleProductByChannelIdAndProductIds($channel_id,$fliter_product_ids);
        } else {
            $product_channel_lists = $product_channel_handler->getProductChannelByChannelId($channel_id);
        }

        $tmp_product_lists = array();
        $fliter_product_ids = array(); //  重新组装待处理的商品id
        foreach ($product_channel_lists as $product) {
            //若价格筛选存在且最小售价不在筛选区间则跳过此次循环
            if(!empty($req['minPrice']) && !empty($req['maxPrice'])){
                if((float)$product['price'] < $req['minPrice'] || (float)$product['price'] > $req['maxPrice']) {
                    continue;
                }
            }
            $tmp_product_lists[$product['product_id']]['id'] = $product['product_id'];
            $tmp_product_lists[$product['product_id']]['enterprise_id'] = $product['enterprise_id'];
            $tmp_product_lists[$product['product_id']]['brand_id'] = $product['brand_id'];
            $tmp_product_lists[$product['product_id']]['brandname'] = (string) $product['brand_name'];
            $tmp_product_lists[$product['product_id']]['parent_brand_name'] = is_null($product['parent_brand_name']) ? '' : $product['parent_brand_name'];
            $tmp_product_lists[$product['product_id']]['parent_brand_id'] = is_null($product['parent_brand_id']) ? '' : $product['parent_brand_id'];;
            $tmp_product_lists[$product['product_id']]['name'] = (string) $product['name'];
            $tmp_product_lists[$product['product_id']]['icon_url'] = self::fullImgUrl($product['icon_url']);
            $tmp_product_lists[$product['product_id']]['mass_packing'] = (string) $product['sell_unit_string'];
            $tmp_product_lists[$product['product_id']]['remark'] = (string) $product['remark'];
            $tmp_product_lists[$product['product_id']]['channel_price'] = (string)$product['price'];
            $tmp_product_lists[$product['product_id']]['sort_price'] = (float)$product['price'];
            $tmp_product_lists[$product['product_id']]['sort'] = (float)$product['sort']; // 商品排序
            $fliter_product_ids[] = $product['product_id']; //重新组装待处理的商品id
        }
        $product_sale_valume = $product_channel_handler->getSalesVolumeByProductIds($fliter_product_ids); // 得到销量信息
        $product_sku_list = $product_channel_handler->getOnsaleAttrByProductIdsAndChannelId($fliter_product_ids,$channel_id);// 得到sku信息
        \Biz\Market\Product::handelSkuListPriceByChannelIdAndEnterpriseId($product_sku_list,$channel_id,$enterprise_id); // 根据渠道id批量处理sku价格，与参与活动状态
        $result_product_list = array();
        $activity_list  = array();
        foreach ($tmp_product_lists as $product_id=>$item) {
            $result_product_list[$product_id] = $item;
            $result_product_list[$product_id]['sales_valume'] = isset($product_sale_valume[$product_id]) ? $product_sale_valume[$product_id] : 0;
            $result_product_list[$product_id]['sku_info'] = isset($product_sku_list[$product_id]) ? $product_sku_list[$product_id] : array();
            if (isset($product_sku_list[$product_id][0]['join_market_type'])){
                $result_product_list[$product_id]['activity_info'] = array(array('id'=>1)); // 只需标记参与活动即可
                $activity_list[$product_id] = $result_product_list[$product_id]; //使其在原分类中依然可以展示
                /*放入特价促销中*/
                $result_product_list[$product_id]['brand_id'] = 0;
                $result_product_list[$product_id]['brandname'] = '特价促';
                $result_product_list[$product_id]['parent_brand_id'] = 0;
                $result_product_list[$product_id]['parent_brand_name'] = '特价促';
                /*放入特价促销中*/
            } else {
                $result_product_list[$product_id]['activity_info'] = array();
            }
        }
        $result_product_list_merge = array_merge($result_product_list,$activity_list);
        $result_product_list = array_values($result_product_list_merge);
        self::sortByBrand($result_product_list);
        self::sortByProduct($result_product_list);
        $result['product_list'] =$result_product_list;
    }

    /**
     * 补全图片信息
     * @param $icon_url
     * @return string
     */
    protected static function fullImgUrl($icon_url)
    {
        $image_domain = 'http://image.freshqiao.com';
        $image_url = $icon_url == '/' ? $image_domain . $icon_url : $image_domain . '/' . $icon_url;
        return $image_url;
    }

    protected function low_array_column($input, $columnKey, $indexKey = NULL){
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array)$input AS $key => $row){
            if ($columnKeyIsNumber){
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            }else{
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if (!$indexKeyIsNull){
                if ($indexKeyIsNumber){
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && ! empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                }else{
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }


    /**
     *  // 按brand升序排序
     * @param $product_list
     * @return mixed
     */
    protected static function sortByBrand(&$product_list)
    {
        $brand_ids = array();
        foreach ($product_list as $product) {
            $brand_ids[] = $product['brand_id'];
        }
        array_multisort($brand_ids, SORT_ASC, $product_list);
    }

    /**
     * 根据商品sort字段排序
     * @param $product_list
     */
    private static function sortByProduct(&$product_list)
    {
        $product_brand_list = array();
        foreach ($product_list as $product) {
            $product_brand_list[$product['brand_id']][] = $product;
        }
        foreach ($product_brand_list as $brand_id => $brand_product) {
            $sort_ids = array();
            foreach ($brand_product as $product) {
                $sort_ids[] = $product['sort'];
            }
            array_multisort($sort_ids, SORT_DESC, $product_brand_list[$brand_id]);
        }
        $product_list_temp = array();
        foreach ($product_brand_list as $brand_product) {
            foreach ($brand_product as  $product) {
                $product_list_temp[] = $product;
            }
        }
        $product_list = $product_list_temp;
    }
}